package org.example.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Optional;
import java.util.Scanner;

/**
 * @author 邓天天
 * @date 2021/4/5 8:50
 */
public class GroupChatClient {
    private final String HOST = "127.0.0.1";
    private final int PORT = 10009;
    private Selector selector;
    private SocketChannel channel;
    private String userName;

    public GroupChatClient() throws IOException {
        selector = Selector.open();
        channel = SocketChannel.open(new InetSocketAddress(HOST,PORT));
        channel.configureBlocking(false);
        channel.register(selector, SelectionKey.OP_READ);
        userName = channel.getLocalAddress().toString().substring(1);
        System.out.println("客户端准备好了");
    }

    public void sendInfo(String info) {
        info = userName + "说" + info;
        try {
            channel.write(ByteBuffer.wrap(info.getBytes(StandardCharsets.UTF_8)));
        } catch (IOException exception) {
            exception.printStackTrace();
        }
    }
    // 从服务器读取消息
    public void readInfo() {
        try {
            while (selector.select() > 0) {
                final Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
                while (keyIterator.hasNext()) {
                    final SelectionKey selectionKey = keyIterator.next();
                    if (selectionKey.isReadable()) {
                        SocketChannel sc = (SocketChannel) selectionKey.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        sc.read(buffer);
                        System.out.println(new String(buffer.array()).trim());
                    }
                    keyIterator.remove();
                }
            }
        }catch (IOException exception ) {
            exception.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception{
        GroupChatClient chatClient = new GroupChatClient();
        new Thread(()->{
            while (true) {
                chatClient.readInfo();
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();

                }
            }
        }).start();
        final Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String msg = scanner.nextLine();
            chatClient.sendInfo(msg);
        }
    }

}
